package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.entity.*;
import com.example.mapper.PictureMapper;
import com.example.mapper.RepairMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 账单表业务处理
 **/
@Service
public class UserRepairService {

    @Resource
    private RepairMapper repairMapper;
    @Resource
    private PictureMapper pictureMapper;

    /**
     * 新增
     */
    @Transactional
    public void add(Repair repair) {
        repair.setReportTime(DateUtil.now());
        // TODO 报修单号
        // 获取当前的日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        repair.setRepairNumber("RO"+now.format(formatter)+repair.getUserId());
//        Account currentUser = TokenUtils.getCurrentUser();
//        if (RoleEnum.USER.name().equals(currentUser.getRole())) {  // 只有用户才记录用户ID
//            bill.setUserId(currentUser.getId());
//        }

        repairMapper.insert(repair);

        List<String> pictures = repair.getPictures();
        if(pictures!=null){
            for(String temp : pictures){
                Picture picture = new Picture();
                picture.setRepairNumber(repair.getRepairNumber());
                picture.setCover(temp);
                picture.setType("USER");
                pictureMapper.insert(picture);
            }
        }

    }

    public void notice(List<String> toUser, String message){
        String accessToken = this.getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("touser", String.join("|", toUser));
        requestBody.put("msgtype", "text");
        requestBody.put("agentid", 1000002);
        Map<String, String> text = new HashMap<>();
        text.put("content", message);
        requestBody.put("text", text);
        requestBody.put("safe", 0);

        try {
            // 将Map转换为JSON字符串
            String jsonRequestBody = JSON.toJSONString(requestBody);

            // 构建请求头
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);
            // 指定响应返回json格式
            requestHeaders.add("accept", "application/json");

            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonRequestBody, requestHeaders);
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

            // 获取响应体
            String responseStr = response.getBody();
            System.out.println(responseStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String getAccessToken() {
        // 构建URL，包含查询参数
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?" +
                "corpid=wwed13ff8d54add547&" +
                "corpsecret=_0fcBVZIGtG1GXuquy9_1VnQCXy1QatiU2oylhDqNrU";

        // 使用RestTemplate执行GET请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String responseStr = response.getBody();

        // 解析响应json字符串
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        repairMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            repairMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Repair repair) {
        repairMapper.updateById(repair);

        List<String> pictures = repair.getPictures();
        if(pictures!=null){
            for(String temp : pictures){
                Picture picture = new Picture();
                picture.setRepairNumber(repair.getRepairNumber());
                picture.setCover(temp);
                picture.setType("USER");
                pictureMapper.insert(picture);
            }
        }

    }

    /**
     * 根据ID查询
     */
    public Repair selectById(Integer id) {
        return repairMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Repair> selectAll(Repair repair) {
        return repairMapper.selectAll(repair);
    }

    /**
     * 分页查询
     */
    public PageInfo<Repair> selectPage(Repair repair, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Repair> list = repairMapper.selectAll(repair);
        List<Repair> resList = new ArrayList<>();
        for (Repair repair1 : list) {
            Picture picture = new Picture();
            picture.setRepairNumber(repair1.getRepairNumber());
            picture.setType("USER");
            List<Picture> pictures = pictureMapper.selectAll(picture);
            List<String> reportImages = pictures.stream().map(Picture::getCover)
                    .collect(Collectors.toList());
            repair1.setReportImages(reportImages);
            picture.setType("WORKER");
            List<Picture> picturesW = pictureMapper.selectAll(picture);
            List<String> repairImages = picturesW.stream().map(Picture::getCover)
                    .collect(Collectors.toList());
            repair1.setRepairImages(repairImages);
            resList.add(repair1);
        }
        return PageInfo.of(resList);
    }

    public List<Repair> count(String type) {
        Repair repair = new Repair();
        repair.setRepairType(type);
        List<Repair> repairList = repairMapper.selectAll(repair);  // 根据当前登录的用户ID查询到所有的账单信息
        List<String> categoryList = repairMapper.selectCategoryByType(type);
        List<Repair> list = new ArrayList<>();
//        for (String category : categoryList) {
//            Repair r = new Repair();
//            r.setCategory(category);
//            // 统计出当前这个分类的所有的金额汇总
//            BigDecimal categorySum = billList.stream().filter(bi -> bi.getCategory().equals(category)).map(Bill::getMoney).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
//            // 返回当前分类的总金额
//            b.setMoney(categorySum);
//            // 得到账单的百分比
//            b.setPercent(categorySum.divide(sum, 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).intValue());
//            list.add(b);
//        }
        return list;
    }

    public void evaluateById(Repair repair) {
        Repair r = new Repair();
        r.setId(repair.getId());
        r.setComments(repair.getComments());
        r.setRating(repair.getRating());
        r.setRepairStatus("已完成");
        repairMapper.updateById(r);
    }
}